package net.qiqbframework.messaging.intercepting;



import net.qiqbframework.messaging.InterceptorChain;
import net.qiqbframework.messaging.Message;
import net.qiqbframework.messaging.correlation.CorrelationDataProvider;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import net.qiqbframework.messaging.MessageHandlerInterceptor;
import net.qiqbframework.messaging.task.MessageTask;

public class CorrelationDataInterceptor<T extends Message<?>> implements MessageHandlerInterceptor<T> {

    private final List<CorrelationDataProvider> correlationDataProviders;

    /**
     * Initializes the interceptor that registers given {@code correlationDataProviders} with the current Unit of Work.
     *
     * @param correlationDataProviders The CorrelationDataProviders to register with the Interceptor
     */
    public CorrelationDataInterceptor(CorrelationDataProvider... correlationDataProviders) {
        this(Arrays.asList(correlationDataProviders));
    }

    /**
     * Initializes the interceptor that registers given {@code correlationDataProviders} with the current Unit of Work.
     *
     * @param correlationDataProviders The CorrelationDataProviders to register with the Interceptor
     */
    public CorrelationDataInterceptor(Collection<CorrelationDataProvider> correlationDataProviders) {
        this.correlationDataProviders = new ArrayList<>(correlationDataProviders);
    }

    @Override
    public Object handle(@Nonnull MessageTask<? extends T> unitOfWork, @Nonnull InterceptorChain interceptorChain)
            throws Exception {
        correlationDataProviders.forEach(unitOfWork::registerCorrelationDataProvider);
        return interceptorChain.proceed();
    }

}
